package com.luck.picture.lib;

import android.content.Context;
import android.content.ContextWrapper;
import android.content.res.Configuration;
import android.graphics.Color;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.VideoView;

import com.danikula.videocache.HttpProxyCacheServer;
import com.luck.picture.lib.utils.NetWorkUtils;
import com.luck.picture.lib.widget.CommonDialog;

import java.io.File;

/**
 * @author wenchao
 */
public class VideoPreviewActivity extends PictureBaseActivity implements MediaPlayer.OnErrorListener,
        MediaPlayer.OnPreparedListener, MediaPlayer.OnCompletionListener {

    private String videoPath = "";
    private VideoView mVideoView;
    private int mPositionWhenPaused = -1;
    private ProgressBar progressBar;
    private CommonDialog dialog;

    @Override
    public int getResourceId() {
        return R.layout.activity_video_preview;
    }

    @Override
    protected void initWidgets() {
        super.initWidgets();
        videoPath = getIntent().getStringExtra("video_path");
        RelativeLayout rlBody = findViewById(R.id.rl_body);
        mVideoView = findViewById(R.id.video_view);
        mVideoView.setBackgroundColor(Color.BLACK);
        progressBar = findViewById(R.id.progressBar);
        mVideoView.setOnCompletionListener(this);
        mVideoView.setOnPreparedListener(this);
        rlBody.setOnClickListener(v -> finish());
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        //设置全屏
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        super.onCreate(savedInstanceState);
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        setContentView(R.layout.activity_video_preview);
        mVideoView = findViewById(R.id.video_view);
        mVideoView.setBackgroundColor(Color.BLACK);
        progressBar = findViewById(R.id.progressBar);
        mVideoView.setOnCompletionListener(this);
        mVideoView.setOnPreparedListener(this);
        mVideoView.setOnClickListener(v -> finish());
        startPlay();
    }

    @Override
    public void onStart() {
        // Play Video
        //判断网络状态
        if (NetWorkUtils.is3gConnected(this) && videoPath.startsWith("http")) {
            dialog = new CommonDialog(this, "您当前正在使用移动网络，继续播放？", () -> {
                startPlay();
            }, () -> finish(), "取消", "继续");
            dialog.setCancelable(false);
            dialog.setCanceledOnTouchOutside(false);
            dialog.show();
            dialog.setOnKeyListener((dialog, keyCode, event) -> {
                if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
                    cancelDialog();
                    finish();
                    return true;
                }
                return false;
            });
        } else {
            startPlay();
        }
        super.onStart();
    }

    private void cancelDialog() {
        if (isFinishing()) {
            return;
        }
        if (null != dialog && dialog.isShowing()) {
            dialog.dismiss();
        }
    }

    private void startPlay() {
        if (videoPath.startsWith("http")) {
            final HttpProxyCacheServer proxy = PictureApplication.getProxy();
            if (proxy == null) {
                return;
            }
            String proxyUrl = proxy.getProxyUrl(videoPath);
            mVideoView.setVideoPath(proxyUrl);
            mVideoView.start();
        } else {
            mVideoView.setVideoPath(videoPath);
            mVideoView.start();
        }
    }

    @Override
    public void onPause() {
        // Stop video when the activity is pause.
        mPositionWhenPaused = mVideoView.getCurrentPosition();
        mVideoView.stopPlayback();
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        mVideoView = null;
        super.onDestroy();
    }

    @Override
    public void onResume() {
        // Resume video player
        if (mPositionWhenPaused >= 0) {
            mVideoView.seekTo(mPositionWhenPaused);
            mPositionWhenPaused = -1;
        }
        super.onResume();
    }

    @Override
    public boolean onError(MediaPlayer player, int arg1, int arg2) {
        return false;
    }

    @Override
    public void onCompletion(MediaPlayer mp) {
        mVideoView.start();
    }

    @Override
    protected void attachBaseContext(Context newBase) {
        super.attachBaseContext(new ContextWrapper(newBase) {
            @Override
            public Object getSystemService(String name) {
                if (Context.AUDIO_SERVICE.equals(name)) {
                    return getApplicationContext().getSystemService(name);
                }
                return super.getSystemService(name);
            }
        });
    }

    @Override
    public void onPrepared(MediaPlayer mp) {
        mp.setOnInfoListener((mp1, what, extra) -> {
            if (what == MediaPlayer.MEDIA_INFO_VIDEO_RENDERING_START) {
                // video started
                mVideoView.setBackgroundColor(Color.TRANSPARENT);
                progressBar.setVisibility(View.GONE);
                return true;
            }
            return false;
        });
    }

    @Override
    public void onBackPressed() {
        finish();
        cancelDialog();
        super.onBackPressed();
    }
}
